const fs = require("fs");

const supenAgent = require("superagent");
var baseOut = "./output";
// var inPath = "D:\\quickView\\";
var inPath = "http://192.168.0.202:8081/quickView/";

function testAndBuild(path) {
  return new Promise((resolve) => {
    if (!fs.existsSync(path)) {
      fs.mkdirSync(path, (err, data) => {
        if (err) {
          console.log(err);
          resolve();
          return;
        }
        resolve();
      });
    } else {
      resolve();
    }
  });
}

async function download(pathOut, pathIn) {
  const ifNetUrl = pathIn.includes("http");
  return new Promise((resolve, reject) => {
    if (!fs.existsSync(pathIn) && !ifNetUrl) {
      console.log("文件：" + pathIn + "不存在");
      resolve();
      return;
    }

    const rs = ifNetUrl ? supenAgent.get(pathIn).buffer(true) : fs.createReadStream(pathIn);

    const ws = fs.createWriteStream(pathOut);
    rs.pipe(ws);
    ws.on("finish", (err) => {
      if (err) {
        console.log(err);
        return;
      }
      resolve();
    });
  });
}

async function doItem(item) {
  const t0 = new Date().getTime();
  const quickViewUrl = item.quickViewUrl;
  let a = baseOut;
  for (let p of quickViewUrl.split("\\")) {
    if (!p.includes(".")) {
      a = a + "/" + p;
      testAndBuild(a);
    }
  }
  await download(baseOut + "/" + quickViewUrl, inPath + quickViewUrl);
  console.log(`文件${quickViewUrl}操作结束，耗时：${new Date().getTime() - t0}ms`);
}

(function () {
  const t0 = new Date().getTime();
  fs.readFile("./data.txt", "utf-8", async (error, data) => {
    if (error) {
      console.log(error);
      return;
    }

    const res = JSON.parse(data);
    const list = res.data.list;
    for (let item of list) {
      await doItem(item);
    }
    console.log(`执行结束！耗时:${new Date().getTime() - t0}ms`);
  });
})();
